<?php
/**
* This file holds a class for Application_Model_ColorMapper.
* @package busmap
*/

/**
* This class holds Application_Model_ColorMapper class, that maps Color objects to the database entries.
* @package busmap
*/
class Application_Model_ColorMapper
{
	protected $_dbTable;
 
   	/**
	* Function that sets the database table for the Color objects.
	*/
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
 
   	/**
	* Function that gets the database table for the Color objects.
	*/
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Color');
		}
		return $this->_dbTable;
	}

	/**
	* Function that deletes a Color entry from the database based on the id value given.
	*/
	public function deleteEntry($id){
		$where = $this->getDbTable()->getAdapter()->quoteInto('id = ?', $id);
		$this->getDbTable()->delete($where);
	}

	/**
	* Function that saves the Color object given to it to the database.
	* If id value is set, existing entry will be updated.
	* Otherwise a new entry will be created.
	*/
	public function save(Application_Model_Color $color)
	{
		$data = array(
			'name'   => $color->getName(),
			'redValue' => $color->getRedValue(),
			'greenValue' => $color->getGreenValue(),
			'blueValue' => $color->getBlueValue()
		);
 
		if (null === ($id = $color->getId())) {
			unset($data['id']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id = ?' => $id));
		}
	}
 
	/**
	* Function that finds a entry with the id value given.
	* Given reference object will be used to hold the data.
	*/
	public function find($id, Application_Model_Color $color)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$color->setId($row->id)
			  ->setRedValue($row->redValue)
			  ->setGreenValue($row->greenValue)
			  ->setBlueValue($row->blueValue)
			  ->setName($row->name);
	}

	/**
	* Function that finds all Color entries from the database.
	* Returns an array with Color objects corresponding to the found entries.
	*/
	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Color();
			$entry->setId($row->id)
				  ->setRedValue($row->redValue)
				  ->setGreenValue($row->greenValue)
				  ->setBlueValue($row->blueValue)
				  ->setName($row->name);
			$entries[] = $entry;
		}
		return $entries;
	}
}